#include "hrt.h"

/*初始化  SysTick*/
static uint64_t timer_micros_counter = 0;
//static uint64_t timer_millis_counter = 0;
//void SysTick_Init(void)
//{
//	/* SystemFrequency / 1000    1ms中断一次
//	 * SystemFrequency / 100000	 10us中断一次
//	 * SystemFrequency / 1000000 1us中断一次
//	 */
//	if (SysTick_Config(72000000 / 50))
//  {
//    /* Capture error */
//    while (1);
//  }
//}

void hrt_init(){
	TIM_TimeBaseInitTypeDef TIM_BaseInitStructure;
	NVIC_InitTypeDef NVIC_InitStructure;

	//Step1.时钟设置：启动TIM1
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);

	//Step2.中断NVIC设置：允许中断，设置优先级
	NVIC_InitStructure.NVIC_IRQChannel = TIM1_UP_IRQn;  //更新事件
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;  //抢占优先级0
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;      //响应优先级1
	NVIC_InitStructure.NVIC_IRQChannelCmd =  ENABLE;  //允许中断
	NVIC_Init(&NVIC_InitStructure);  //写入设置


	TIM_BaseInitStructure.TIM_Period = 20000; //向上计数至1000
	TIM_BaseInitStructure.TIM_Prescaler = 71; //进行72预分频
	TIM_BaseInitStructure.TIM_ClockDivision = 0;
	TIM_BaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
	TIM_BaseInitStructure.TIM_RepetitionCounter = 0;
	TIM_TimeBaseInit(TIM1,&TIM_BaseInitStructure);

	TIM_ClearFlag(TIM1, TIM_FLAG_Update); //清中断，以免一启用中断后立即产生中断
	TIM_ITConfig(TIM1, TIM_IT_Update, ENABLE); //使能TIM1中断源
	TIM_Cmd(TIM1, ENABLE); //TIM1总开关：开启
}
//定时器1中断服务程序
void TIM1_UP_IRQHandler(void){
	if(TIM_GetITStatus(TIM1,TIM_IT_Update)==SET){
		timer_micros_counter++;
		TIM_ClearITPendingBit(TIM1,TIM_FLAG_Update);	//清中断
	}
}
hrt_abstime hrt_absolute_time(){
	asm("CPSID  I"); //关中断
	uint64_t time_micros = timer_micros_counter * 20000;
	uint64_t tcnt = TIM1->CNT;//
	asm("CPSIE  I"); //开中断
	return  time_micros+tcnt;
}

